// Copyright 2010 Google Inc. All Rights Reserved.
package br.org.imazon.sad;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;

import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

/**
 * Servlet that acts as a proxy to the Earth Engine API.
 * @author thau@google.com (David Thau)
 */
@SuppressWarnings("serial")
public class EEAccessServlet extends HttpServlet {

	  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
		  doPost(req, resp);
	  }
	  
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    try {
      HttpSession session = req.getSession();
      
      String auth = Authenticate.auth(session,"gestalt");

      if (auth != null) {
        String path = req.getPathInfo();
        String responseText = "";
        if (path != null) {
          if (path.equals("/search")) {
            String[] params = {"q"};
            QueryString qs = new QueryString(params, req);
            responseText = EEAccess.getSearch(auth, qs.toString());

          } else if (path.equals("/info")) {
            String[] params = {"id"};
            QueryString qs = new QueryString(params, req);
            responseText = EEAccess.getInfo(auth, qs.toString());

          } else if (path.equals("/list")) {
            String[] params = {"id", "num", "starttime", "endtime"};
            QueryString qs = new QueryString(params, req);
            responseText = EEAccess.getList(auth, qs.toString());
            
          } else if (path.equals("/value")) {
              String[] params =
          {"image", "version","fields"};
          QueryString qs = new QueryString(params, req);
          responseText = EEAccess.getValue(auth, qs.toString());
          System.out.println(responseText);

          } else if (path.equals("/mapid") || path.equals("/thumb")) {
        	  QueryString qs;
        	  if (req.getParameter("image") != null) {
        		  
                String[] params =
                  {"image", "version", "bands", "min", "max", "gain", "bias", "gamma", "palette"};
                qs = new QueryString(params, req);
        	  } else {
        		 String[] params =
                  {"id", "version", "bands", "min", "max", "gain", "bias", "gamma", "palette"};
        		 qs = new QueryString(params, req);
        	  }
             
            if (path.equals("/mapid")) {
              responseText = EEAccess.getMapId(auth, qs.toString());
            } else if (path.equals("/thumb")) {
              String[] thumbParams = {"width", "height", "region", "pixel_bb", "format"};
              qs.add(thumbParams, req);
              responseText = EEAccess.getThumbId(auth, qs.toString());
            }
          }
        }
        PrintWriter out = resp.getWriter();
        out.print(responseText);
      } else {
        RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/authError.jsp");
        rd.forward(req, resp);
      }

    } catch (AuthenticationException e) {
      e.printStackTrace();

    } catch (ServiceException e) {
      e.printStackTrace();

    } catch (ServletException e) {
      e.printStackTrace();
    }
  }
}

/**
 * A utility for constructing query strings.
 */
class QueryString {

  private String query = "";

  public QueryString(String[] params, HttpServletRequest req) {
		  encode(params, req);
  }

  public void add(String[] params, HttpServletRequest req) {
    encode(params, req);
  }

  private void encode(String[] params, HttpServletRequest req) {
    try {
      for (int i = 0; i < params.length; i++) {
        String param = params[i];
        String value = req.getParameter(param);

        // Nothing is appended if the value is missing.
        if (value == null) continue;

        if (query.length() > 0) query += "&";
        if (req.getMethod().equals("GET")) {
        	query += URLEncoder.encode(param, "UTF-8");
        } else {
        	query += param;
        }
        query += "=";
        if (req.getMethod().equals("GET")) {
        	query += URLEncoder.encode(value, "UTF-8");
        } else {
        	query += value;
        }
      }
    } catch (UnsupportedEncodingException ex) {
      throw new RuntimeException("Broken VM does not support UTF-8");
    }
  }

  public String getQuery() {
    return query;
  }

  public String toString() {
    return getQuery();
  }
}
